package quick.frame.service.ui;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.afollestad.materialdialogs.MaterialDialog;
import java.util.HashMap;
import java.util.Map;
import butterknife.BindView;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.yokeyword.fragmentation.SupportFragment;
import quick.frame.core.app.ConfigKeys;
import quick.frame.core.app.Configurator;
import quick.frame.core.app.RxManager;
import quick.frame.core.base.activity.BaseCompatActivity;
import quick.frame.core.net.RestCreator;
import quick.frame.core.net.rx.RxHelper;
import quick.frame.core.rxbus.RxBus;
import quick.frame.core.ui.toolbar.CommonToolbar;
import quick.frame.core.ui.toolbar.Style;
import quick.frame.core.util.NavigationUtils;
import quick.frame.core.util.SpUtils;
import quick.frame.core.util.ToastUtils;
import quick.frame.core.widgets.MovingImageView;
import quick.frame.core.widgets.MovingViewAnimator;
import quick.frame.service.R;
import quick.frame.service.api.SpdApi;
import quick.frame.service.bean.ResultBean;
import quick.frame.service.bean.WareHouse;
import quick.frame.service.contains.DataKeys;
import quick.frame.service.contains.HttpMethodContains;
import quick.frame.service.ui.fragment.ThreeParentFragemnt;
import quick.frame.service.ui.fragment.TwoParentFragemnt;
import quick.frame.service.helper.BottomNavigationViewHelper;
import quick.frame.service.ui.fragment.OneParentFragemnt;

public class HomeActivity extends BaseCompatActivity {

    @BindView(R.id.fl_container)
    FrameLayout flContainer;
    @BindView(R.id.bviv_bar)
    BottomNavigationView bottomNavigationView;
    @BindView(R.id.nv_menu)
    NavigationView nvMenu;
    @BindView(R.id.dl_root)
    DrawerLayout dlRoot;

    //BottomNavigationView bottomNavigationView;
    public static final int FIRST = 0;
    public static final int SECOND = 1;
    public static final int THIRD = 2;
    public static final int FOURTH = 3;
    public static final int FIFTH = 4;

    private SupportFragment[] mFragments = new SupportFragment[3];

    private MovingImageView mivMenu;
    private CircleImageView civHead;
    // 再点一次退出程序时间设置
    private static final long WAIT_TIME = 2000L;
    private long TOUCH_TIME = 0;
    @Override
    protected void initView(Bundle savedInstanceState) {
        initWareHouse();
        if(savedInstanceState == null){
            mFragments[FIRST] = OneParentFragemnt.newInstance();
            mFragments[SECOND] = TwoParentFragemnt.newInstance();
            mFragments[THIRD] = ThreeParentFragemnt.newInstance();
          loadMultipleRootFragment(R.id.fl_container, FIRST,
                    mFragments[FIRST],
                    mFragments[SECOND],
                    mFragments[THIRD]);
          //loadRootFragment(R.id.fl_container,mFragments[FIRST]);
        }else{
            mFragments[FIRST] = findFragment(OneParentFragemnt.class);
            mFragments[SECOND] =findFragment(TwoParentFragemnt.class);
            mFragments[THIRD] = findFragment(ThreeParentFragemnt.class);
        }

        NavigationUtils.disableNavigationViewScrollbars(nvMenu);
        mivMenu = (MovingImageView) nvMenu.getHeaderView(0).findViewById(R.id.miv_menu);
        civHead = (CircleImageView) nvMenu.getHeaderView(0).findViewById(R.id.civ_head);

        civHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dlRoot.closeDrawer(GravityCompat.START);
                bottomNavigationView.setSelectedItemId(R.id.menu_item_personal);
            }
        });

       BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView
                .OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_item_home:
                        showHideFragment(mFragments[FIRST]);
                        break;
                    case R.id.menu_item_gank_io:
                        showHideFragment(mFragments[SECOND]);
                        break;
                  //  case R.id.menu_item_movie:
                        //showHideFragment(mFragments[THIRD]);
                 //       break;
                 //   case R.id.menu_item_book:
                        //showHideFragment(mFragments[FOURTH]);
                //        break;
                   case R.id.menu_item_personal:
                        showHideFragment(mFragments[THIRD]);
                        break;
                }
                return true;
            }
        });

        nvMenu.getMenu().findItem(R.id.item_model).setTitle(SpUtils.getNightModel(mContext) ?
                "夜间模式" : "日间模式");
        nvMenu.setNavigationItemSelectedListener(new NavigationView
                .OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.group_item_github:

                        break;
                    case R.id.group_item_more:

                        break;
                    case R.id.group_item_qr_code:

                        break;
                    case R.id.group_item_share_project:

                        break;
                    case R.id.item_model:
                        SpUtils.setNightModel(mContext, !SpUtils.getNightModel(mContext));
                        HomeActivity.this.reload();
                        break;
                    case R.id.item_about:

                        break;
                }

                item.setCheckable(false);
                dlRoot.closeDrawer(GravityCompat.START);
                return true;
            }
        });

        dlRoot.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
                mivMenu.pauseMoving();
            }

            @Override
            public void onDrawerOpened(@NonNull View drawerView) {
                if (mivMenu.getMovingState() == MovingViewAnimator.MovingState.stop) {
                    mivMenu.startMoving();
                } else if (mivMenu.getMovingState() == MovingViewAnimator.MovingState.pause) {
                    mivMenu.resumeMoving();
                }
            }

            @Override
            public void onDrawerClosed(@NonNull View drawerView) {
                mivMenu.stopMoving();
            }

            @Override
            public void onDrawerStateChanged(int newState) {
                if (mivMenu.getMovingState() == MovingViewAnimator.MovingState.stop) {
                    mivMenu.startMoving();
                } else if (mivMenu.getMovingState() == MovingViewAnimator.MovingState.pause) {
                    mivMenu.resumeMoving();
                }
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_home;
    }

    @Override
    protected void initData() {
        super.initData();
        //        Logger.e("RxBus.get().register(this)");
        RxBus.get().register(this);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //        Logger.e("RxBus.get().unRegister(this)");
        RxBus.get().unRegister(this);
    }

    @Override
    public void onBackPressedSupport() {

        if (dlRoot.isDrawerOpen(GravityCompat.START)) {
            dlRoot.closeDrawer(GravityCompat.START);
            return;
        }

        if (getFragmentManager().getBackStackEntryCount() > 1) {
            //如果当前存在fragment>1，当前fragment出栈
            pop();
        } else {
            //如果已经到root fragment了，2秒内点击2次退出
            if (System.currentTimeMillis() - TOUCH_TIME < WAIT_TIME) {
                setIsTransAnim(false);
                finish();
            } else {
                TOUCH_TIME = System.currentTimeMillis();
                ToastUtils.showToast(R.string.press_again);
            }
        }
    }

/*    @Override
    public void onOpen() {
        if (!dlRoot.isDrawerOpen(GravityCompat.START)) {
            dlRoot.openDrawer(GravityCompat.START);
        }
    }*/

    @Override
    protected CommonToolbar initToolBar() {
       return CommonToolbar.Builder(this)
               .setStatusBarStyle(Style.TRANSPARENT)
               .addLeftIcon(1,R.drawable.icon_back,null)
               .addLeftText(2,"返回",null)
               .addRightText(3,"选择仓库",null)
               .setBackgroundColorRes(R.color.colorPrimary)// 背景颜色
              .apply();
    }

    private int i = 0;
    private void initWareHouse(){
        //RxRestClient.builder()
        Map<String,Object> data = new HashMap<>();
        data.put("method", HttpMethodContains.WAREHOUSE_QUERY);
        Observable<ResultBean<WareHouse>> compose = RestCreator
                .createApi(SpdApi.class, Configurator.getInstance().getConfiguration(ConfigKeys.API_HOST))
                .getWareHouseList(data)
                .compose(RxHelper.<ResultBean<WareHouse>>rxSchedulerHelper());
        Disposable subscribe = compose.subscribe(new Consumer<ResultBean<WareHouse>>() {

            @Override
            public void accept(ResultBean<WareHouse> wareHouseResultBean) throws Exception {
                if(wareHouseResultBean.isSuccess()){
                    getToolBar().getViewByTag(3).setOnClickListener(l->{
                        new MaterialDialog.Builder(HomeActivity.this)
                                .title(R.string.woreHourse)
                                .items(wareHouseResultBean.getRows())
                                //  .itemsDisabledIndices(1, 3)
                                .itemsCallbackSingleChoice(
                                        i,
                                        (dialog, view, which, text) -> {
                                            i= which;
                                            Configurator.put(DataKeys.WAREHOUSE,wareHouseResultBean.getRows().get(i));
                                            ((TextView)getToolBar().getViewByTag(3)).setText(text);
                                            return true; // allow selection
                                        })
                                .positiveText(R.string.md_choose_label)
                                .onPositive(((dialog, which) -> {
                                    ToastUtils.showToast("选择成功");
                                }))
                                .canceledOnTouchOutside(false)
                                .show();
                    });
                }else{
                    throw new Exception(wareHouseResultBean.getMsg());
                }
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                ToastUtils.showToast(throwable.getMessage());
            }
        });
      RxManager rxManager = new RxManager();
      rxManager.register(subscribe);

    }

}
